import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import storage from '@/utils/storage';
const constantRoutes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'layout',
        component: () => import('@/pages/layout/index.vue'),
        children: [
            {
                path: '/homeManager',
                name: '首页管理',
                component: () => import('@/pages/homeManager/index.vue'),
            },
            {
                path: '/articleManager',
                name: '文章管理',
                component: () => import('@/pages/articleManager/index.vue'),
                children: [
                    {
                        path: '/articleManager/list',
                        name: '文章列表',
                        component: () =>
                            import('@/pages/articleManager/list.vue'),
                    },
                    {
                        path: '/articleManager/create',
                        name: '创建文章',
                        component: () =>
                            import('@/pages/articleManager/create.vue'),
                    },
                ],
            },
            {
                path: '/mailManager',
                name: '留言管理',
                component: () => import('@/pages/mailManager/index.vue'),
            },
        ],
    },
    {
        path: '/login',
        name: '登录',
        component: () => import('@/pages/login/index.vue'),
    },
    {
        path: '/404',
        name: '404',
        component: () => import('@/pages/error-page/404.vue'),
    },
];
export { constantRoutes };

export const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes,
});
// 全局路由钩子，先判断token是否存在，不存在则跳转登陆
router.beforeEach(async (to, from, next) => {
    if (!storage.get('token') && to.path !== '/login') {
        // 将用户重定向到登录页面
        next('/login');
    } else {
        next();
    }
});
